<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="平台名称" prop="platformName">
        <el-input
          v-model="queryParams.platformName"
          placeholder="请输入平台名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="平台类型" prop="typeCode">
        <el-select v-model="queryParams.typeCode" placeholder="请选择平台类型" clearable>
          <el-option
            v-for="type in platformTypes"
            :key="type.typeCode"
            :label="type.typeName"
            :value="type.typeCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
          <el-option label="测试中" value="2" />
          <el-option label="连接失败" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fiscale:platform:add']"
        >添加平台</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="platformList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="平台名称" align="center" prop="platformName" :show-overflow-tooltip="true" />
      <el-table-column label="平台类型" align="center" prop="typeName" />
      <el-table-column label="API Key" align="center" prop="apiKey" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.apiKey">{{ scope.row.apiKey.substring(0, 8) }}***</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="同步状态" align="center" prop="syncStatus">
        <template slot-scope="scope">
          <dict-tag :options="syncStatusOptions" :value="scope.row.syncStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="最后同步时间" align="center" prop="lastSyncTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastSyncTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleSync(scope.row)"
            v-hasPermi="['fiscale:platform:sync']"
            :loading="scope.row.syncing"
          >立即同步</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fiscale:platform:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fiscale:platform:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台授权配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="平台类型" prop="typeId" v-if="!form.configId">
          <el-select v-model="form.typeId" placeholder="请选择平台类型" @change="handleTypeChange">
            <el-option
              v-for="type in platformTypes"
              :key="type.typeId"
              :label="type.typeName"
              :value="type.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="平台名称" prop="platformName">
          <el-input v-model="form.platformName" placeholder="请输入平台实例名称" />
        </el-form-item>
              
        <el-form-item label="API Key" prop="apiKey">
          <el-input v-model="form.apiKey" placeholder="请输入API密钥" type="password" show-password />
        </el-form-item>
        
        <!-- 动态配置字段 -->
        <div v-if="configFields.length > 0">
          <h4 style="margin: 20px 0 10px 0; color: #606266;">API配置信息</h4>
          <el-form-item 
            v-for="field in configFields" 
            :key="field.field"
            :label="field.label" 
            :prop="'configData.' + field.field"
            :rules="field.required ? [{ required: true, message: field.label + '不能为空', trigger: 'blur' }] : []"
          >
            <!-- 文本输入框 -->
            <el-input 
              v-if="field.type === 'text'"
              v-model="form.configData[field.field]" 
              :placeholder="field.placeholder"
            />
            <!-- 密码输入框 -->
            <el-input 
              v-else-if="field.type === 'password'"
              v-model="form.configData[field.field]" 
              :placeholder="field.placeholder"
              type="password"
              show-password
            />
            <!-- 下拉选择框 -->
            <el-select 
              v-else-if="field.type === 'select'"
              v-model="form.configData[field.field]" 
              :placeholder="'请选择' + field.label"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            <div class="form-field-tip" v-if="field.description">{{ field.description }}</div>
          </el-form-item>
        </div>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="info" @click="testConnection" :loading="testing">测试连接</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlatform, getPlatform, delPlatform, addPlatform, updatePlatform, getPlatformTypes, getPlatformConfigFields, testPlatformConnection, syncPlatformData } from "@/api/fiscale/platform";

export default {
  name: "Platform",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台授权配置表格数据
      platformList: [],
      // 平台类型选项
      platformTypes: [],
      // 配置字段
      configFields: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 测试中状态
      testing: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        platformName: null,
        typeCode: null,
        status: null
      },
      // 表单参数
      form: {
        configData: {}
      },
      // 表单校验
      rules: {
        typeId: [
          { required: true, message: "平台类型不能为空", trigger: "change" }
        ],
        platformName: [
          { required: true, message: "平台名称不能为空", trigger: "blur" }
        ],
        apiKey: [
          { required: true, message: "API Key不能为空", trigger: "blur" }
        ]
      },
      // 状态字典
      statusOptions: [
        { label: "停用", value: "0" },
        { label: "启用", value: "1" },
        { label: "测试中", value: "2" },
        { label: "连接失败", value: "3" }
      ],
      // 同步状态字典
      syncStatusOptions: [
        { label: "未同步", value: "0" },
        { label: "同步中", value: "1" },
        { label: "同步成功", value: "2" },
        { label: "同步失败", value: "3" }
      ]
    };
  },
  created() {
    this.getList();
    this.getPlatformTypes();
  },
  methods: {
    /** 查询平台授权配置列表 */
    getList() {
      this.loading = true;
      listPlatform(this.queryParams).then(response => {
        this.platformList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询平台类型列表 */
    getPlatformTypes() {
      getPlatformTypes().then(response => {
        this.platformTypes = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        configId: null,
        platformName: null,
        typeId: null,
        typeCode: null,
        apiKey: null,
        configData: {},
        status: "1",
        remark: null
      };
      this.configFields = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台授权配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.configId || this.ids[0];
      getPlatform(configId).then(response => {
        this.form = response.data;
        // 解析配置数据
        if (this.form.configData) {
          this.form.configData = JSON.parse(this.form.configData);
        } else {
          this.form.configData = {};
        }
        
        // 加载配置字段
        if (this.form.typeCode) {
          this.loadConfigFields(this.form.typeCode);
        }
        
        this.open = true;
        this.title = "修改平台授权配置";
      });
    },
    /** 平台类型改变事件 */
    handleTypeChange(typeId) {
      const selectedType = this.platformTypes.find(type => type.typeId === typeId);
      if (selectedType) {
        this.form.typeCode = selectedType.typeCode;
        this.loadConfigFields(selectedType.typeCode);
      }
    },
    /** 加载配置字段 */
    loadConfigFields(typeCode) {
      getPlatformConfigFields(typeCode).then(response => {
        if (response.data) {
          this.configFields = JSON.parse(response.data);
          // 初始化配置数据
          this.configFields.forEach(field => {
            if (!this.form.configData[field.field]) {
              this.$set(this.form.configData, field.field, '');
            }
          });
        }
      });
    },
    /** 测试连接 */
    testConnection() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.testing = true;
          const testData = {
            typeCode: this.form.typeCode,
            configData: JSON.stringify(this.form.configData)
          };
          
          testPlatformConnection(testData).then(response => {
            this.$modal.msgSuccess("连接测试成功");
            this.testing = false;
          }).catch(() => {
            this.testing = false;
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 序列化配置数据
          const submitData = { ...this.form };
          submitData.configData = JSON.stringify(this.form.configData);
          
          if (submitData.configId != null) {
            updatePlatform(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatform(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 同步按钮操作 */
    handleSync(row) {
      this.$modal.confirm('是否确认同步平台"' + row.platformName + '"的数据？').then(() => {
        // 设置同步中状态
        this.$set(row, 'syncing', true);
        
        syncPlatformData(row.configId).then(response => {
          this.$modal.msgSuccess("同步任务已启动");
          this.$set(row, 'syncing', false);
          this.getList(); // 刷新列表状态
        }).catch(() => {
          this.$set(row, 'syncing', false);
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configIds = row.configId || this.ids;
      this.$modal.confirm('是否确认删除平台授权配置编号为"' + configIds + '"的数据项？').then(function() {
        return delPlatform(configIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.form-field-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.el-form-item {
  margin-bottom: 18px;
}

h4 {
  font-weight: 500;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}
</style>